package com.loong.web.suppert.handle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.loong.web.suppert.intercept.auth.AuthController;
import com.loong.web.suppert.intercept.checkpoint.CheckpointController;
import com.loong.web.suppert.intercept.cookie.CookieController;
import com.loong.web.suppert.intercept.request.RequestController;
import com.loong.web.suppert.intercept.statistic.StatisticController;

/**
 * 拦截器
 * 
 * @author 张成轩
 */
public class InterceptHandler extends HandlerInterceptorAdapter {

	/** 权限控制器 */
	private AuthController authController;
	/** 访问检测器 */
	private CheckpointController checkpointController;
	/** 访问统计器 */
	private StatisticController statisticController;
	/** Cookie处理器 */
	private CookieController cookieController;
	/** 请求处理器 */
	private RequestController requestController;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		boolean succ;
		if (checkpointController != null) {
			// 访问检测
			succ = checkpointController.control(request, response);
			if (!succ)
				return false;
		}
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			if (cookieController != null)
				// Cookie处理
				cookieController.control(request, response);
			if (authController != null) {
				// 权限控制
				succ = authController.control(request, response, (HandlerMethod) handler);
				if (!succ)
					return false;
			}
			if (requestController != null)
				// 请求处理器
				requestController.control(request, (HandlerMethod) handler);
			if (statisticController != null)
				// 统计器
				statisticController.control(request, (HandlerMethod) handler);
		}
		return true;
	}

	/**
	 * @param authController 权限控制器
	 */
	public void setAuthController(AuthController authController) {

		this.authController = authController;
	}

	/**
	 * @param checkpointController 访问检测器
	 */
	public void setCheckpointController(CheckpointController checkpointController) {

		this.checkpointController = checkpointController;
	}

	/**
	 * @param statisticController 访问统计器
	 */
	public void setStatisticController(StatisticController statisticController) {

		this.statisticController = statisticController;
	}

	/**
	 * @param cookieController Cookie处理器
	 */
	public void setCookieController(CookieController cookieController) {

		this.cookieController = cookieController;
	}

	/**
	 * @param requestController 请求处理器
	 */
	public void setRequestController(RequestController requestController) {

		this.requestController = requestController;
	}
}
